package a08_回溯算法;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a16_全排列2复习1
 * </p>
 *
 * @author flyduck
 * @since 2025/1/6
 */
public class a16_全排列2复习1 {

    public static void main(String[] args) {
        a16_全排列2复习1 test = new a16_全排列2复习1();
        int[] nums = new int[]{1,1,2};
        List<List<Integer>> lists = test.permuteUnique(nums);
        System.out.println("lists = " + lists);
    }

    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        boolean[] used = new boolean[nums.length];
        Arrays.sort(nums);
        traversal(result, path, nums, used);
        return result;
    }

    private void traversal(List<List<Integer>> result,
                           LinkedList<Integer> path,
                           int[] nums,
                           boolean[] used){
        if (path.size() == nums.length) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if(used[i]){//如果使用过就跳过
                continue;
            }
            if(i > 0 && nums[i] == nums[i-1] && !used[i-1]){//前一个相同，并且没有处理过，处理过是树枝去重，没处理是树干去重
                continue;
            }

            path.add(nums[i]);
            used[i] = true;
            traversal(result, path, nums, used);
            path.removeLast();
            used[i] = false;
        }
    }
}
